Page({
    data: {
        keyword: '',
        searchType: 'title',
        searchTypeText: '题名',
        searchTypeIndex: 0,
        searchTypes: [{
                label: '题名',
                value: 'bookTitle'
            },
            {
                label: '著者',
                value: 'author'
            },
            {
                label: '出版社',
                value: 'bookPress'
            },
            {
                label: 'ISBN',
                value: 'isbn'
            },
        ],
        historyList: [],
        hotList: [],
        showActionSheet: false,
        bookList: [],
        bookCoverUrl : 'https://ov-library-1316830564.cos.ap-guangzhou.myqcloud.com/bookCover%2F',
        defaultCover : '/resource/images/defaultCover.png'
    },

    onLoad() {
        // 1. 加载本地历史记录
        const history = wx.getStorageSync('history') || [];
        this.setData({
            historyList: history
        });

        // 2. 加载热门搜索（从后端接口）
        wx.request({
            url: 'http://localhost:8080/books/hotSearch',
            success: (res) => {
                this.setData({
                    hotList: res.data.data || []
                });
            }
        });

        this.setData({
            showActionSheet: false
        });
    },

    onInput(e) {
        this.setData({
            keyword: e.detail.value
        });
    },

    onSearch() {
        const {
            historyList
        } = this.data;
        // if (!keyword) return;

        // // 调用后端搜索接口
        // wx.request({
        //     url: 'https://example.com/api/search',
        //     method: 'GET',
        //     data: {
        //         [searchType]: keyword
        //     },
        //     success: (res) => {
        //         console.log('搜索结果:', res.data);
        //         // 跳转到结果页或展示结果逻辑
        //     }
        // });

        // 获取请求参数
    const searchType = this.data.searchTypes[this.data.searchTypeIndex].value
    const keyword = this.data.keyword.trim()

    // 空值校验
    if (!keyword) {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      })
      return
    }

    // 显示加载状态
    // this.setData({ isLoading: true })

    // 发送请求
    wx.request({
      url: 'http://localhost:8080/books/query', // 替换为实际接口
      method: 'GET',
      data: {
        search_type: searchType,
        keyword: keyword
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          // 成功响应
          const list = res.data.data || [] // 对应 Result.ok().setData(list)
          this.setData({
            bookList: list, // 假设返回数据在 list 字段
          })

        } else {
          // 处理错误响应
          wx.showToast({
            title: res.data.msg || '请求失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        // 网络错误处理
        console.error('搜索失败:', err)
        wx.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
      }
    })

        // 保存到历史记录（最多10个）
        const updated = [keyword, ...historyList.filter(k => k !== keyword)].slice(0, 10);
        this.setData({
            historyList: updated
        });
        wx.setStorageSync('history', updated);
    },

    onHistoryTagTap(e) {
        const keyword = e.currentTarget.dataset.keyword;
        this.setData({
            keyword
        }, this.onSearch);
    },

    onHotTagTap(e) {
        const keyword = e.currentTarget.dataset.keyword;
        this.setData({
            keyword
        }, this.onSearch);
    },

    clearHistory() {
        wx.removeStorageSync('history');
        this.setData({
            historyList: []
        });
    },

    showSearchType() {
        this.setData({
            showActionSheet: true
        });
        console.log(this.data.showActionSheet);
    },

    hideSearchType() {
        this.setData({
            showActionSheet: false
        });
    },

    selectSearchType(e) {
        const type = e.currentTarget.dataset.type;
        const typeItem = this.data.searchTypes.find(item => item.value === type);
        this.setData({
            searchType: type,
            searchTypeText: typeItem.label,
            showActionSheet: false
        });
    },

    onSearchTypeChange(e) {
        const index = e.detail.value
        const selected = this.data.searchTypes[index]
        this.setData({
            searchTypeIndex: index,
            searchTypeText: selected.label,
            // 如果需要保存 value 值（如提交搜索时用），可以存在 data 中：
            searchTypeValue: selected.value
        })
    },

    goToBookDetail(event) {
        console.log("event:"+event)
        const bookId = event.currentTarget.dataset.id;
        wx.navigateTo({
          url: `/pages/books/detailed/detailed?id=${bookId}`
        });
      },
    
      clearSearch(){
          this.setData({
            bookList: [], 
            keyword: ''
          })
      },

});